﻿using CoreShop.Library;
using CoreShop.Library.Units;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Model.UI;
using CoreShop.Services;
using FastMember;
using MySqlX.XDevAPI.Common;
using NAudio.CoreAudioApi;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using static CoreShop.Model.FromBody.DataResultModel;
using static CoreShop.Services.PosRemoteServices;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace CoreShop.App.Units.Interface
{
    public class SystemApiUtil
    {
        /// <summary>
        /// 支付修改
        /// </summary>
        /// <param name="vipInfo"></param>
        /// <returns></returns>
        public static async Task<ReturnModel> BatchInsertPayInfo(sysuser sysuser, List<PayAccountModel> payAccountModel)
        {
            string postStr = payAccountModel.ToJsonString();
            //var result = HttpHelper.PostSendMessage(baseUrl, $"{SERVER.Pay}{API.BatchInsertPayInfo}", postStr, 60, "", sysuser);
            var url = $"{SERVER.Pay}{API.BatchInsertPayInfo}";
            ReturnModel returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, url, postStr, 60, "", AppConstVars.sysUser);
            return returnModel;
        }

        /// <summary>
        /// 刷新令牌
        /// </summary>
        public static async Task<bool> RefreshTokenAsync(corecmsstore store, sysuser user)
        {
            var logRs = await LoginByPos(user.userName, Security.Decrypt(user.passWord), store);
            if (logRs.code == 0)
            {
                LoginBody loginBody = JsonConvert.DeserializeObject<LoginBody>(logRs.data.ToString());
                if (new sysuserServices().SetLoginData(ref user, loginBody, AppConstVars.sysStore))
                {
                    AppConstVars.sysUser = user;
                }
                return true;
            }
            return false;
        }

        ///// <summary>
        ///// 提交已激活的AI码
        ///// </summary>
        ///// <returns></returns>
        public static async Task<ReturnModel> PostAddActivateCode(sysuser sysuser, corecmsstore store, AiCodeGetInfoListModel AiInfo)
        {
            JObject keyValues = new JObject();

            keyValues.Add(new JProperty("aiId", AiInfo.aiId));
            keyValues.Add(new JProperty("beginDate", DateTime.Now.ToString("yyyy-MM-dd")));
            keyValues.Add(new JProperty("branchId", store.branchId));
            keyValues.Add(new JProperty("branchName", store.branchName));
            keyValues.Add(new JProperty("deviceId", store.deviceId));
            keyValues.Add(new JProperty("endDate", DateTime.Now.AddYears(1).ToString("yyyy-MM-dd")));
            keyValues.Add(new JProperty("remark", ""));
            keyValues.Add(new JProperty("status", 0));
            string[] Date = new string[] { DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.AddYears(1).ToString("yyyy-MM-dd") };

            //return HttpHelper.PostSendMessage(baseUrl, $"{SERVER.Base}{API.InsertBaseAiBind}"
            //    , keyValues.ToJsonString(), 60, "", sysuser);
            var url = $"{SERVER.Base}{API.InsertBaseAiBind}";
            ReturnModel returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, url, keyValues.ToJsonString(), 60, "", AppConstVars.sysUser);
            return returnModel;
        }


        ///// <summary>
        ///// 获取激活码
        ///// </summary>
        ///// <returns></returns>
        public static async Task<ReturnModel> GetActivateCodeList(sysuser sysuser, string AiCode = null)
        {
            ReturnModel res = new ReturnModel();
            JObject keyValues = new JObject();

            keyValues.Add(new JProperty("pageNum", 1));
            keyValues.Add(new JProperty("pageSize", 9999));
            keyValues.Add(new JProperty("status", 0));
            if (!string.IsNullOrEmpty(AiCode))
            {
                keyValues.Add(new JProperty("aiCode", AiCode));
            }
            try
            {
                //return HttpHelper.PostSendMessage(baseUrl, $"{SERVER.Base}{API.GetBaseAiList}",
                //    keyValues.ToJsonString(), 60, "", sysuser);

                var url = $"{SERVER.Base}{API.GetBaseAiList}";
                ReturnModel returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, url, keyValues.ToJsonString(), 60, "", AppConstVars.sysUser);
                return returnModel;
            }
            catch (Exception ex) { }
            return null;
        }


        /// <summary>
        /// 保存付款方式
        /// </summary>
        /// <param name="vipInfo"></param>
        /// <returns></returns>
        public static async Task<AsyncReturnModel> SavePayments(BalanceTypeDataModel dataModel)
        {
            AsyncReturnModel res = new AsyncReturnModel();
            try
            {
                var url = $"{SERVER.Order}{API.SaveBalanceType}";
                ReturnModel returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, url, JsonConvert.SerializeObject(dataModel), 60, "", AppConstVars.sysUser);
                res = JsonConvert.DeserializeObject<AsyncReturnModel>(returnModel.MessageOrString);
            }
            catch (Exception ex) { res.code = 1; res.msg = ex.Message; }
            return res;
        }



        public static async Task<List<BalanceTypeDataModel>> GetBalanceType()
        {
            try
            {
                //var postData = new { posUsed = 1 };
                var postData = new { };
                ReturnModel returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, $"{SERVER.Order}{API.GetBalanceType}", JsonConvert.SerializeObject(postData), 60, "", AppConstVars.sysUser);

                var res = JsonConvert.DeserializeObject<AdminUiCallBack>(returnModel.MessageOrString);
                List<BalanceTypeDataModel> list = JsonConvert.DeserializeObject<List<BalanceTypeDataModel>>(res.data.ToString());
                if (list != null)
                {
                    var paymentsService = new corecmspaymentsService();
                    var bl = paymentsService.Update(a => new corecmspayments()
                    {
                        isEnable = false,posUsed = 0,rechargeUsed = 0
                    }, a => a.id > 1);

                    var thisPaymentList = paymentsService.GetList();
                    foreach (var item in list)
                    {
                        var findItem = thisPaymentList.Find(p => p.code == item.balanceTypeCode);
                        if (findItem != null)
                        {
                            findItem.tenantBalanceTypeId = item.tenantBalanceTypeId;
                            findItem.posUsed = item.posUsed;
                            findItem.rechargeUsed = item.rechargeUsed;
                            findItem.isEnable = item.status == 0 ? false : true;
                            findItem.corpId = AppConstVars.sysStore.corpId;
                            findItem.content = JsonConvert.SerializeObject(item);
                            findItem.name = item.balanceTypeName;
                            thisPaymentList.Add(findItem);
                        }
                        else
                        {
                            corecmspayments payments = new corecmspayments();
                            payments.name = item.balanceTypeName;
                            payments.code = item.balanceTypeCode;
                            payments.sort = 0;
                            payments.isEnable = item.status == 0 ? false : true;
                            payments.corpId = AppConstVars.sysStore.corpId;
                            payments.tenantBalanceTypeId = item.tenantBalanceTypeId;
                            payments.posUsed = item.posUsed;
                            payments.rechargeUsed = item.rechargeUsed;
                            payments.content = JsonConvert.SerializeObject(item);
                            thisPaymentList.Add(payments);
                        }
                    }
                    var returnValue = paymentsService.InsertOrUpdate(thisPaymentList);

                    ProcessUtil.GetSystemPayment();
                }
                return list;
            }
            catch (Exception ex)
            {

            }
            return null;
        }
                

        /// <summary>
        /// 交班
        /// </summary>
        /// <param name="vipInfo"></param>
        /// <returns></returns>
        public static async Task<AdminUiCallBack> SendPostDuty(dynamic DutyInfo)
        {
            AdminUiCallBack res = new AdminUiCallBack();
            try
            {
                var url = $"{SERVER.Pos_service}{API.InsertPosDuty}";
                //string retStr = Library.HttpHelper.httpPost(url, JsonConvert.SerializeObject(DutyInfo), _token);
                //res = JsonConvert.DeserializeObject<AdminUiCallBack>(retStr);

                ReturnModel returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, url, JsonConvert.SerializeObject(DutyInfo), 60, "", AppConstVars.sysUser);
                res = JsonConvert.DeserializeObject<AdminUiCallBack>(returnModel.MessageOrString);
            }
            catch (Exception ex) { res.code = 1; res.msg = ex.Message; }
            return res;
        }


        /// <summary>
        /// 前台注册
        /// </summary>
        /// <returns></returns>
        public static async Task<UserRegisterResult> PosRegister(string userName, string password, string deviceId)
        {
            UserRegisterResult result = new UserRegisterResult();
            AdminUiCallBack res = new AdminUiCallBack();
            try
            {
                FMRegister register = new FMRegister();
                Hashtable ht = new Hashtable();
                ht["userName"] = userName;
                ht["password"] = password;
                ht["deviceId"] = deviceId;
                ht["deviceNo"] = deviceId;
                ht["deviceType"] = 1;
                string postStr = JsonConvert.SerializeObject(ht);
                //string retStr = Library.HttpHelper.httpPost(sWebUrl, postStr);
                ReturnModel returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, $"{API.userRegister}", postStr, 60, "", AppConstVars.sysUser);
                res = JsonConvert.DeserializeObject<AdminUiCallBack>(returnModel.MessageOrString);
                if (res == null)
                {
                    result.msg = "远程服务无法访问";
                    result.code = 1;
                    return result;
                }
                if (res.code != 200)
                {
                    result.msg = res.msg;
                    result.code = 1;
                    return result;
                }
                register = JsonConvert.DeserializeObject<FMRegister>(res.data.ToString());
                result.data = register;
            }
            catch (Exception e)
            {
                res.msg = e.Message;
                res.code = 1;
            }
            result.code = 0;
            return result;
        }


        /// <summary>
        /// 获取用户权限
        /// </summary>
        public static async void GetUserRouters(sysuser sysuser)
        {
            JObject keyValues = new JObject();
            DateTime dateTime = DateTime.Now;
            try
            {
                new sysuserServices().SetSysroleposAuto(sysuser);//自动添加所有权限
                
                ReturnModel returnModel = await HttpHelperAsync.GetDataAsync(ApiConsVars.baseUrl, $"{SERVER.System}{API.GetRouters}", 60, AppConstVars.sysUser);
                GsMenuListModel gsMenuListModel = returnModel.MessageOrString.JsonToEntity<GsMenuListModel>();
                if (gsMenuListModel == null || gsMenuListModel.data == null)
                {
                    return;
                }
                if (gsMenuListModel.code != 200) return;

                var userRoles = gsMenuListModel.data;
                var rmoRoles = new List<sysrolepos>();

                if ((userRoles != null) && (userRoles.Count > 0))   
                {
                    new sysroleposServices().Update(a => new sysrolepos()
                    {
                        status = false,
                        visible = false,
                    }, a => a.sysUserId == sysuser.id);
                }
                foreach (var role in userRoles)
                {
                    var rmoRole = new sysrolepos();
                    rmoRole.roleId = sysuser.id.ToString() + role.component;
                    rmoRole.sysUserId = sysuser.id;
                    rmoRole.component = role.component;
                    rmoRole.menu_name = role.menuName;
                    rmoRole.status = !CommFunc.Int32StringToBoolean(role.status);
                    rmoRole.visible = !CommFunc.Int32StringToBoolean(role.visible);
                    rmoRoles.Add(rmoRole);
                }
                await new sysroleposServices().InsertOrUpdateAsync(rmoRoles);
                AppConstVars.sysUserRole = ProcessUtil.GetUserRolePos(AppConstVars.sysUser.id);//获取前台权限
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 获取用户角色
        /// </summary>
        public static async void GetUserRoleInfo(sysuser sysuser)
        {
            try
            {
                string para = $"{SERVER.System}{API.GetUserRole}?id={sysuser.posRoleId}";
                ReturnModel returnModel = await HttpHelperAsync.GetDataAsync(ApiConsVars.baseUrl, para, 60, AppConstVars.sysUser);
                AdminUiCallBack res = JsonConvert.DeserializeObject<AdminUiCallBack>(returnModel.MessageOrString);

                if ((res == null) || (res.code != 200)) return;

                sysroleinfo sysroleinfo = JsonConvert.DeserializeObject<sysroleinfo>(res.data.ToString());
                await new sysroleinfoServices().InsertOrUpdateAsync(sysroleinfo);                
                AppConstVars.sysUserRoleInfo = ProcessUtil.GetUserRoleInfo(CommFunc.ConvertToInt64(AppConstVars.sysUser.posRoleId));
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 用户后台登录
        /// </summary>
        /// <returns></returns>
        public static async Task<sysuser> GetUserLogin(string userName, string password)
        {
            var store = new corecmsstoreServices().GetFirst(p => p.id > 0);
            LoginData loginInfo = new LoginData();
            var sysuser = await LoginByPos(userName, password, store);
            return null;
        }

        public static async Task<AdminUiCallBack> LoginByPos(string userName, string passWord, corecmsstore store)
        {
            AdminUiCallBack res = new AdminUiCallBack();
            try
            {
                string tenantId = "";
                if (store != null) tenantId = store.corpId.ToString();
                string sWebUrl = ApiConsVars.baseUrl + $"{API.loginByPos}";
                dynamic posData = new
                {
                    username = userName,
                    password = passWord,
                    dataMap = new { store.deviceId, store.registerNo, tenantId }
                };
                string postStr = JsonConvert.SerializeObject(posData);
                string retStr = await HttpHelperAsync.PostDataAsync(sWebUrl, postStr);
                res = JsonConvert.DeserializeObject<AdminUiCallBack>(retStr);
                if (res == null)
                {
                    res.msg = "远程服务无法访问";
                    res.code = 3;
                    return res;
                }
                if (res.code != 200) return res;
            }
            catch (Exception e)
            {
                res.msg = e.Message;
                res.code = 1;
            }

            res.code = 0;
            return res;
        }


        /// <summary>
        /// 发起付款
        /// </summary>
        /// <param name="payCode"></param>
        /// <param name="amt"></param>
        /// <param name="businessType">支付类型</param>
        /// <param name="mchNo">流水号</param>
        /// <returns></returns>
        public static async Task<ReturnModel> GetPayAccounList(sysuser sysuser)
        {
            JObject keyValues = new JObject();
            //商户ID
            keyValues.Add(new JProperty("tenantId", sysuser.corpId));
            //var result = HttpHelper.PostSendMessage(baseUrl, $"{SERVER.Pay}{API.GetPayAccuntList}", keyValues.ToJsonString(), 60, "", sysuser);
            ReturnModel returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl,$"{SERVER.Pay}{API.GetPayAccuntList}", keyValues.ToJsonString(), 60, "", sysuser);
            return returnModel;
        }

        /// <summary>
        /// 获取系统服务商资料
        /// </summary>
        /// <param name="sysuser"></param>
        /// <returns></returns>
        public static async Task<SysAgenModel> GetSysAgentInfo(string agentId)
        {
            try
            {
                //var url = string.Concat(baseUrl, $"{SERVER.System}{API.SearchSysAgent}", "/", agentId);
                //Hashtable ht = new Hashtable();
                //string retStr = Library.HttpHelper.httpGetString(url, sysuser.ccessToken);
                ReturnModel returnModel = await HttpHelperAsync.GetDataAsync(ApiConsVars.baseUrl, $"{SERVER.System}{API.SearchSysAgent}", 60, AppConstVars.sysUser);
                AdminUiCallBack res = JsonConvert.DeserializeObject<AdminUiCallBack>(returnModel.MessageOrString);
                if (res.code == 200)
                {
                    SysAgenModel data = JsonConvert.DeserializeObject<SysAgenModel>(res.data.ToString());
                    return data;
                }
            }
            catch (Exception ex)
            {

            }
            return null;
        }

        /// <summary>
        /// 获取商户资料
        /// </summary>
        /// <param name="sysuser"></param>
        /// <returns></returns>
        public static async Task<TenantModel> GetTenantInfo()
        {
            try
            {
                //var url = string.Concat(baseUrl, $"{SERVER.System}{API.SystemTenant}", "/", sysuser.corpId.ToString());
                //Hashtable ht = new Hashtable();
                //string retStr = Library.HttpHelper.httpGetString(url, sysuser.ccessToken);
                ReturnModel returnModel = await HttpHelperAsync.GetDataAsync(ApiConsVars.baseUrl, $"{SERVER.System}{API.SystemTenant}", 60, AppConstVars.sysUser);
                AdminUiCallBack res = JsonConvert.DeserializeObject<AdminUiCallBack>(returnModel.MessageOrString);
                if (res.code == 200)
                {
                    TenantModel data = JsonConvert.DeserializeObject<TenantModel>(res.data.ToString());
                    return data;
                }
                UIMessageBox.Show($"访问服务器失败,{res.msg}");
            }
            catch (Exception ex)
            {

            }
            return null;
        }


        ///// <summary>
        ///// 获取支付参数
        ///// </summary>
        ///// <returns></returns>
        public static async Task<ReturnModel> GetPayAccountList(sysuser sysuser)
        {
            ReturnModel res = new ReturnModel();
            JObject keyValues = new JObject();
            keyValues.Add(new JProperty("tenantId", sysuser.corpId));
            try
            {
                ReturnModel returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl,
                    $"{SERVER.Pay}{API.ThirdpartyAccoun}", keyValues.ToJsonString(), 60, "", sysuser);
                return returnModel;
            }
            catch (Exception ex) { }
            return null;
        }

        public static async Task<Image> LoadImageFromUrlAsync(string imageUrl)
        {
            try
            {
                // 使用HttpClient下载图片
                HttpClient _httpClient = new HttpClient();
                byte[] imageData = await _httpClient.GetByteArrayAsync(imageUrl);

                using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageData))
                {
                    return Image.FromStream(stream);
                }
            }
            catch (HttpRequestException ex)
            {
                //Console.WriteLine($"HTTP请求错误: {ex.Message}");
                return null;
            }
            catch (Exception ex)
            {
                //Console.WriteLine($"加载图片时出错: {ex.Message}");
                return null;
            }
        }
    }
}
